<template>
  <el-drawer title="添加" :visible.sync="visible" :wrapper-closable="false">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm">
      <el-form-item label="房间名称" prop="name">
        <el-input v-model="ruleForm.name" :maxlength="30" show-word-limit />
      </el-form-item>
      <el-form-item label="可住人数" prop="number">
        <el-input v-model="ruleForm.number" :maxlength="3" />
      </el-form-item>
      <el-form-item label="房间租金" prop="rent">
        <el-input v-model="ruleForm.rent" :maxlength="5" />
      </el-form-item>
      <el-form-item label="房间备注" prop="remark">
        <el-input
          v-model="ruleForm.remark"
          :maxlength="200"
          type="textarea"
          :rows="2"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="房间照片(最多8张)" prop="photo">
        <el-upload
          ref="uploadRoom"
          accept="image/jpg,image/jpeg,image/png"
          :action="baseUrl + 'api/v1/upload/file'"
          :list-type="listType"
          :on-remove="handleRemove"
          :multiple="multiple"
          :limit="limit"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <div slot="tip" class="el-upload__tip">
          <el-image
            v-for="(url, index) in uploadedImages"
            :key="index"
            :src="url"
            fit="cover"
            style="margin-right: 10px; margin-bottom: 10px;"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即添加</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script>
import { createRoom } from '@/api/dorm'

export default {
  props: {
    id: {
      default: true
    }
  },
  data() {
    return {
      baseUrl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      uploadUrl: 'https://oatest.mouldc.com/api/v1/upload/file',
      listType: 'picture-card',
      multiple: true,
      limit: 8,
      uploadedImages: [],
      visible: false,
      ruleForm: {
        name: '',
        dormitory_id: this.id,
        number: '',
        rent: '',
        remark: '',
        photo: []
      },
      rules: {
        name: [
          { required: true, message: '请输入房间名称', trigger: 'blur' }
        ],
        dormitory_id: [
          { required: true, message: '请输入宿舍id', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入可住人数', trigger: 'blur' }
        ],
        rent: [
          { required: true, message: '请输入宿舍租金', trigger: 'blur' }
        ],
        photo: [
          { required: true, message: '请上传宿舍照片', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.baseUrl = process.env.VUE_APP_UPLOAD
  },
  methods: {
    handleBeforeUpload(file) {
      const img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error('只能上传图片！')
        return false
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return false
      }
      return suffix || suffix2 || suffix3
    },
    handleSuccess(response, file, fileList) {
      // 上传成功的回调函数
      const imageUrl = URL.createObjectURL(file.raw)
      this.uploadedImages.push(imageUrl)
      this.ruleForm.photo.push(response.data.path)
    },
    handleRemove(file) {
      this.ruleForm.photo.forEach((item, index) => {
        if (item === file.response.data.path) {
          this.ruleForm.photo.splice(index, 1)
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = {
            ...this.ruleForm,
            photo: JSON.stringify(this.ruleForm.photo)
          }
          // this.ruleForm.photo = JSON.stringify(this.ruleForm.photo)
          createRoom(params).then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            // this.ruleForm.photo = JSON.parse(this.ruleForm.photo)
            this.$parent.refresh()
            this.visible = false
            this.$refs.uploadRoom.clearFiles()
            console.log(res)
          }).catch(err => {
            this.$message({
              message: err?.response?.data?.message || '房间创建失败',
              type: 'error'
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs.uploadRoom.clearFiles()
    }
  }
}
</script>
<style lang="scss" scoped>
.demo-ruleForm {
    margin-left: 20px;
}
</style>
